import { ElMessage } from "element-plus";
import type { IOptions } from "./types";

const request = async <T>(url: string, options?: IOptions<T>): Promise<T> => {
  const { data, error } = await useFetch(url, options);

  // 请求失败
  if (error.value) {
    const message = error.value.message;
    ElMessage.error(message);
    return Promise.reject(message);
  }

  const result = data.value!; // 非空断言

  // 请求成功&功能失败
  if (result.code !== 200) {
    const message = result.message;
    ElMessage.error(message);
    return Promise.reject(message);
  }

  // 请求成功&功能成功
  return result.data;
};

export default request;
